package com.cardbaobao.cardbabyclient.ui.adapter.base;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

import java.util.ArrayList;
import java.util.List;

/**
 * 单item通用适配器(这里不能改)
 *
 * @param <T>
 * @author zad
 */
public abstract class CommonAdapter<T> extends BaseAdapter {

    protected LayoutInflater mInflater;
    protected Context mContext;
    protected List<T> mData = new ArrayList<>();
    protected final int mItemLayoutId;

    public CommonAdapter(Context mContext, List<T> mData, int mItemLayoutId) {
        mInflater = LayoutInflater.from(mContext);
        this.mContext = mContext;
        if (mData != null) this.mData.addAll(mData);
        this.mItemLayoutId = mItemLayoutId;
    }

    public void setDataSource(List<T> mData) {
        //这里被sb改了，别乱动，我怕
        if (mData == null) return;
        this.mData.clear();
        this.mData.addAll(mData);
        notifyDataSetChanged();
    }

    public void addData(List<T> mData) {
        if (mData == null) return;
        this.mData.addAll(mData);
        notifyDataSetChanged();
    }

    public List<T> getData() {
        return this.mData;
    }


    @Override
    public int getCount() {
        return mData == null ? 0 : mData.size();
    }

    @Override
    public T getItem(int position) {
        return mData.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        final ViewHolder viewHolder = getViewHolder(position, convertView, parent);
        convert(viewHolder, getItem(position), position);
        return viewHolder.getConvertView();
    }

    public abstract void convert(ViewHolder holder, T item, int position);

    private ViewHolder getViewHolder(int position, View convertView, ViewGroup parent) {
        return ViewHolder.get(mContext, convertView, parent, mItemLayoutId, position);
    }
}
